package it.tref.eclipse.wicket.plugin.wizards;

import it.tref.eclipse.wicket.plugin.WicketFunActivator;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWizard;

/**
 * This wizard create a new Wicket Web Page java and html file.
 * By default create the properties file also, but it can be avoid by uncheking the correspondig button
 * 
 * @author tref.af
 */
public class WicketFunNewPageWizard extends Wizard implements INewWizard
{
	private WicketFunNewComponentWizard page;
	//private ISelection selection;
	private boolean createProperties;

	/**
	 * Constructor for WicketFunNewPageWizard.
	 */
	public WicketFunNewPageWizard() {
		super();
		setNeedsProgressMonitor(true);
	}
	
	/**
	 * Adding the page to the wizard.
	 */
	public void addPages() {
		page = new WicketFunNewComponentWizard(WicketFunNewComponentWizard.WicketComponent.Page);
		addPage(page);
	}

	/**
	 * This method is called when 'Finish' button is pressed in
	 * the wizard. We will create an operation and run it
	 * using wizard as execution context.
	 */
	public boolean performFinish()
	{
		Display.getDefault().asyncExec(new Runnable() {
			
			@Override
			public void run() {
				createProperties = page.isCreatePropertiesChecked();
			}
		});
		
		IRunnableWithProgress op = new IRunnableWithProgress()
		{
			public void run(IProgressMonitor monitor) throws InvocationTargetException
			{
				try {
					doFinish(monitor);
				} catch (CoreException e) {
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
		};
		
		try
		{
			getContainer().run(true, false, op);
		} catch (InterruptedException e) {
			return false;
		} catch (InvocationTargetException e) {
			Throwable realException = e.getTargetException();
			MessageDialog.openError(getShell(), "Error", realException.getMessage());
			return false;
		}
		return true;
	}
	
	/**
	 * Create the wicket files
	 * 
	 * @param monitor
	 * @throws CoreException
	 */
	private void doFinish(IProgressMonitor monitor) throws CoreException
	{
		try {
			page.createType(monitor);
		} catch (InterruptedException e1) {
			throwCoreException("Unable to create java file");
		}
		
		monitor.beginTask("Creating html file", 1);
		
		IPath hpath = page.getCreatedType().getPath().removeFileExtension().addFileExtension("html");
		IFile hfile = ResourcesPlugin.getWorkspace().getRoot().getFile(hpath);
		
		InputStream stream;
		try {
			stream = openHtmlContentStream();
			if (hfile.exists()) {
				hfile.setContents(stream, true, true, monitor);
			} else {
				hfile.create(stream, true, monitor);
			}
			stream.close();
		} catch (IOException e) {
			throwCoreException("Unable to create html file");
		}
		monitor.worked(1);
		
		if(createProperties)
		{
			monitor.beginTask("Creating properties file", 1);
			IPath ppath = page.getCreatedType().getPath().removeFileExtension().addFileExtension("properties");
			IFile pfile = ResourcesPlugin.getWorkspace().getRoot().getFile(ppath);
			
			try {
				stream = openPropertiesContentStream();
				if (pfile.exists()) {
					pfile.setContents(stream, true, true, monitor);
				} else {
					pfile.create(stream, true, monitor);
				}
				stream.close();
			} catch (IOException e) {
				throwCoreException("Unable to create properties file");
			}
			monitor.worked(1);
		}
	}
	
	private InputStream openHtmlContentStream() throws IOException
	{
		return WicketFunActivator.getDefault().getBundle().getResource("templates/wicket-page.html").openStream();
	}
	
	private InputStream openPropertiesContentStream() throws IOException
	{
		return WicketFunActivator.getDefault().getBundle().getResource("templates/wicket.properties").openStream();
	}

	private void throwCoreException(String message) throws CoreException {
		IStatus status =
			new Status(IStatus.ERROR, "it.tref.eclipse.wicket.plugin", IStatus.OK, message, null);
		throw new CoreException(status);
	}

	/**
	 * We will accept the selection in the workbench to see if
	 * we can initialize from it.
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		//this.selection = selection;
	}
}